// 登录接口和注册接口
const Router = require('@koa/router')
const router = new Router()
const { userLogin, findUser, userRegister } = require('../controllers/index.js')
const { sign, verify, refreshVerify } = require('../utils/jwt.js')
const { escape } = require('../utils/security.js')
router.prefix('/user')//路由前缀，表示所有路由都以/user开头
// 登录接口
router.post('/login', async (ctx) => {
    //1.获取请求体中的账号密码
    //post请求携带的参数都在请求体中
    let { username, password } = ctx.request.body//从请求体中解构账号密码
    username=escape(username)//转译标签，防止sql注入
    password=escape(password)//转译标签，防止sql注入
    //2.验证账号密码是否正确
    //去数据库中查询账号密码是否正确
    try {
        const res = await userLogin(username, password)//res为查找的结果集，为一个数组，就一个元素
        if (res.length) {//当数组不为空时(引用类型转布尔类型都为true)
            let data = {
                id: res[0].id,
                username: res[0].username,
                nickname: res[0].nickname,
                create_time: res[0].create_time,
            }
            const access_token = sign(data, '1h')//生成短token令牌
            const refresh_token = sign(data, '7d')
            ctx.body = {
                code: '1',//逻辑成功
                msg: '登录成功',
                data,
                access_token: access_token,//登录成功后，后端生成一个短token给前端   
                refresh_token: refresh_token
            }
        } else {
            ctx.body = {
                code: '0',//逻辑性错误，账号或密码错误，而不是程序或代码错误
                msg: '账号或密码错误',
            }
        }
    } catch (error) {//程序性错误(代码错误)userLogin报错
        ctx.body = {
            code: '-1',//程序或代码错误
            msg: '服务器异常',
            data: error
        }
    }
})

//注册接口
router.post('/register', async (ctx) => {
    let { username, password, nickname } = ctx.request.body
    if (!username || !password || !nickname) {
        ctx.body = {
            code: '0',
            msg: '账号密码昵称不能为空',
        }
    }
    //转译标签，防止sql注入
    username = escape(username)
    password = escape(password)
    nickname = escape(nickname)
    //检验账号是否存在
    const res = await findUser(username)//不存在则res为[]
    if (res.length) {
        ctx.body = {
            code: '0',
            msg: '账号已存在',
            data: {}
        }
        return
    }
    //写入数据库
    try {
        const result = await userRegister({ username, password, nickname, create_time: Date.now() })
        if (result.affectedRows) {
            ctx.body = {
                code: '1',
                msg: '注册成功',
            }
        } else {
            ctx.body = {
                code: '0',
                msg: '注册失败',
            }
        }
    } catch (error) {
        ctx.body = {
            code: '-1',
            msg: '服务器异常',
            data: error
        }
    }

})

//刷新token
router.post('/refresh', async (ctx) => {
    const { refresh_token } = ctx.request.body
    //校验refresh_token是否有效
    const vaild = refreshVerify(refresh_token)
    if (vaild.id) {//如果长token解密成功
        //创建新的长短token
        const data = {
            id: vaild.id,
            username: vaild.username,
            nikeName: vaild.nikeName,
            create_time: vaild.create_time,
        }
        const access_token = sign(data, '1h')//生成短token令牌
        const refresh_token = sign(data, '7d')//生成长token令牌
        ctx.body = {
            code: '1',
            msg: '刷新成功',
            access_token: access_token,
            refresh_token: refresh_token,
        }
    } else {//长token过期
        ctx.status = 416,
            ctx.body = {
                code: '0',
                msg: '登录过期，请重新登录',
            }
    }
})



//测试接口
router.get('/text', verify(), async (ctx) => {
    ctx.body = {
        code: '1',
        msg: '测试成功',
    }
})
module.exports = router
